﻿using KBWebApi.Common;
using KBWebApi.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KBWebApi.Bll
{
    public class UserBll
    {
        Dal.UserDal userDal = new Dal.UserDal();

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user">登录实体</param>
        /// <returns></returns>
        public async Task<ActionResult> SignIn(UserDto user)
        {

            if (string.IsNullOrWhiteSpace(user.UserId))
            {
                return new JsonResult(new
                {
                    code = 0,
                    message = "请输入用户ID"
                });
            }
            if (string.IsNullOrWhiteSpace(user.Password))
            {
                return new JsonResult(new
                {
                    code = 0,
                    message = "请输入密码"
                });
            }
            //秘钥
            var signkey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("OwnerKBApiFromDXL"));
            //构造token参数
            var options = new TokenProvidorOptions
            {
                Audienc = "https://localhost:5001",
                Issuer = "https://localhost:5001",
                signingCredentials = new SigningCredentials(signkey, SecurityAlgorithms.HmacSha256),
                Expiration = new TimeSpan(07, 00, 00, 00)//token过期时间,7天
            };
            try
            {

                //实例化TokenProvider对象
                var tep = new TokenProvider(options);
                //获取token
                var token = await tep.GenerateToken(user.UserId, user.Password, true);
                return new JsonResult(new
                {
                    code = 20000,
                    message = token
                });
            }
            catch (Exception ex)
            {
                WriteLog.Writelog("user.AddUser-return=>" + ex.ToString());
                return new JsonResult(new
                {
                    code = 0,
                    message = "错误！请联系管理员！"
                });
            }
        }

        public async Task<ActionResult> GetInfo(string token)
        {
            var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token);
            if(jwt.ValidTo > DateTime.Now)
            {
                string userId = jwt.Claims.ToList()[0].Value;
                UserDto userReturn = await Task.Run(() => Dal.UserDal.GetUserInfo(userId));
                string[] Role = null;
                if (userReturn.Role.Contains(","))
                {
                    Role = userReturn.Role.Split(',');
                }
                else
                {
                    Role = new string[] { userReturn.Role };
                }
                return new JsonResult(new
                {
                    code = 20000,
                    message = new
                    {
                        Roles = Role,
                        Name = userReturn.UserName,
                        userReturn.UserId,
                        userReturn.WorkShopId
                    }
                });
            }
            else
            {
                return new JsonResult(new
                {
                    code = 20001,
                    message = "令牌失效，请重新登录！"
                });
            }
        }

        public async Task<ActionResult> UpdateUserInfo(dynamic dic)
        {
            try
            {
                string userId = dic["UserId"];
                string userName = dic["UserName"];
                string oldPwd = dic["OldPassword"];
                string newPwd = dic["NewPassword"];
                var result = await Task.Run(() => userDal.UpdateUserInfo(userId, userName, oldPwd, newPwd));
                if (result > 0)
                {
                    return new JsonResult(new
                    {
                        code = 20000,
                        message = "更新成功"
                    });
                }
                else
                {
                    return new JsonResult(new
                    {
                        code = 20002,
                        message = "更新失败"
                    });
                }
            }
            catch(Exception ex)
            {
                WriteLog.Writelog("user.UpdateUserInfo=>" + ex.ToString());
                return new JsonResult(new
                {
                    code = 20001,
                    message = "发生错误"
                });
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="dcdUserID"></param>
        /// <param name="psd"></param>
        /// <returns></returns>
        public static async Task<UserDto> GetUser(string dcdUserID, string psd)
        {

            try
            {
                return await Task.Run(() => Dal.UserDal.GetUser(dcdUserID, psd));
            }
            catch (Exception ex)
            {
                WriteLog.Writelog("user.GetUser=>" + ex.ToString());
                return new UserDto { Message = "服务器错误！请联系管理员！" };
            }
        }

        public async Task<ActionResult> NewOrUpdate(UserDto user)
        {
            if (await Task.Run(() => Dal.UserDal.IsExists(user)))
            {
                try
                {
                    var result = await Task.Run(() => userDal.Update(user));
                    if (result > 0)
                    {
                        return new JsonResult(new
                        {
                            code = 20000,
                            message = "更新成功"
                        });
                    }
                    else
                    {
                        return new JsonResult(new
                        {
                            code = 20002,
                            message = "更新失败"
                        });
                    }
                }
                catch (Exception ex)
                {
                    WriteLog.Writelog("User.Update=>" + ex.ToString());
                    return new JsonResult(new
                    {
                        code = 20001,
                        message = "发生错误"
                    });
                }
            }
            else
            {
                try
                {
                    user.CreateDate = DateTime.Now;
                    var result = await Task.Run(() => userDal.NewKBInput(user));
                    if (result > 0)
                    {
                        return new JsonResult(new
                        {
                            code = 20000,
                            message = "新增成功"
                        });
                    }
                    else
                    {
                        return new JsonResult(new
                        {
                            code = 20002,
                            message = "新增失败"
                        });
                    }
                }
                catch (Exception ex)
                {
                    WriteLog.Writelog("User.New=>" + ex.ToString());
                    return new JsonResult(new
                    {
                        code = 20001,
                        message = "发生错误"
                    });
                }
            }
        }

        public async Task<List<UserListView>> GetList(string UserId, string UserName)
        {
            try
            {
                var result = await Task.Run(() => Dal.UserDal.GetList(UserId, UserName));
                ModelHandler<UserListView> modelHandler = new ModelHandler<UserListView>();
                if (result.Rows.Count > 0)
                {
                    var userReturn = modelHandler.FillModel(result);
                    return userReturn;
                }
                return null;
            }
            catch (Exception ex)
            {
                WriteLog.Writelog("User.GetAllList=>" + ex.ToString());
                return null;
            }
        }

        public async Task<ActionResult> Delete(string UserId)
        {
            try
            {
                var result = await Task.Run(() => userDal.Delete(UserId));
                if (result > 0)
                {
                    return new JsonResult(new
                    {
                        code = 20000,
                        message = "删除成功"
                    });
                }
                else
                {
                    return new JsonResult(new
                    {
                        code = 20002,
                        message = "删除失败"
                    });
                }
            }
            catch (Exception ex)
            {
                WriteLog.Writelog("User.Delete=>" + ex.ToString());
                return new JsonResult(new
                {
                    code = 20001,
                    message = "发生错误"
                });
            }
        }
    }
}
